package com.sixetc.sixcontroller.slice;

import com.sixetc.sixcontroller.utils.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.ability.continuation.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PositionLayout;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.bundle.ElementName;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.distributedschedule.interwork.IInitCallback;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

import java.util.Random;

public class MainAbilitySlice extends AbilitySlice {
    private static final String TAG = MainAbilitySlice.class.getSimpleName();
    // 当前应用包名
    private String BUNDLE_NAME = "com.sixetc.sixcontroller";
    // 流转应用包名
    private String REMOTE_BUNDLE_NAME = "com.sixtec.fwapp";
    // 流转FA名称
    private String REMOTE_FA_NAME = "com.sixtec.fwapp.MainAbility";
    // 流转PA名称
    private String REMOTE_PA_NAME = "XXX.XXX.XXX.XXXAbility";
    // 注册流转任务管理服务后返回的Ability token
    private int abilityToken;
    // 用户在设备列表中选择设备后返回的设备ID
    private String selectDeviceId;
    // 用户是否已发起可拉回流转流程
    private boolean isReversibly = false;
    // 获取流转任务管理服务管理类
    private IContinuationRegisterManager continuationRegisterManager;
    // 设置初始化分布式环境的回调
    private IInitCallback iInitCallback = new IInitCallback() {
        @Override
        public void onInitSuccess(String deviceId) {
            LogUtil.info(TAG, "device id success: " + deviceId);
        }

        @Override
        public void onInitFailure(String deviceId, int errorCode) {
            LogUtil.info(TAG, "device id failed: " + deviceId + "errorCode: " + errorCode);
        }
    };
    // 设置流转任务管理服务设备状态变更的回调
    private IContinuationDeviceCallback callback = new IContinuationDeviceCallback() {
        @Override
        public void onDeviceConnectDone(String s, String s1) {
            LogUtil.info(TAG, "onDeviceConnectDone 2");
        }

        @Override
        public void onConnected(ContinuationDeviceInfo deviceInfo) {
            LogUtil.info(TAG, "onConnected 2");
            // 在用户选择设备后设置设备ID
            selectDeviceId = deviceInfo.getDeviceId();
            try {
                // 初始化分布式环境
                DeviceManager.initDistributedEnvironment(selectDeviceId, iInitCallback);
            } catch (RemoteException e) {
                LogUtil.info(TAG, "initDistributedEnvironment failed");
            }
            //更新选择设备后的流转状态
            continuationRegisterManager.updateConnectStatus(abilityToken, selectDeviceId, DeviceConnectState.CONNECTED.getState(), null);
        }

        @Override
        public void onDeviceDisconnectDone(String s) {
            LogUtil.info(TAG, "onDeviceDisconnectDone 1");
        }

        @Override
        public void onDisconnected(String deviceId) {
            LogUtil.info(TAG, "onDisconnected 1");
        }
    };
    // 设置注册流转任务管理服务回调
    private RequestCallback requestCallback = new RequestCallback() {
        @Override
        public void onResult(int result) {
            LogUtil.info(TAG, "requestCallback onResult: "+result);
            abilityToken = result;
        }
    };

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        //super.setUIContent(ResourceTable.Layout_ability_main);

        // 开发者可以自行进行界面设计
        // 为按钮设置统一的背景色
        // 例如通过PositionLayout可以实现简单界面
        PositionLayout layout = new PositionLayout(this);
        ComponentContainer.LayoutConfig config = new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
        layout.setLayoutConfig(config);
        ShapeElement buttonBg = new ShapeElement();
        buttonBg.setRgbColor(new RgbColor(0, 125, 255));
        super.setUIContent(layout);

        //添加功能按钮布局
        addComponents(layout, buttonBg);
        continuationRegisterManager = getContinuationRegisterManager();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 解注册流转任务管理服务
        continuationRegisterManager.unregister(abilityToken, null);
        // 断开流转任务管理服务连接
        continuationRegisterManager.disconnect();
    }


    // 建议开发者按照自己的界面进行按钮设计,示例代码仅供参考
    private static final int OFFSET_X = 100;
    private static final int OFFSET_Y = 100;
    private static final int ADD_OFFSET_Y = 150;
    private static final int BUTTON_WIDTH = 800;
    private static final int BUTTON_HEIGHT = 100;
    private static final int TEXT_SIZE = 50;
    private int offsetY = 0;

    private Button btnShowDeviceList;
    private Button btnStartRemote;
    private Button btnStopRemote;
    private Button btnConnectRemotePA;
    private Button btnControlRemotePA;
    private Button btnDisconnectRemotePA;

    private Button createButton(String text, ShapeElement buttonBg) {
        Button button = new Button(this);
        button.setContentPosition(OFFSET_X, OFFSET_Y + offsetY);
        offsetY += ADD_OFFSET_Y;
        button.setWidth(BUTTON_WIDTH);
        button.setHeight(BUTTON_HEIGHT);
        button.setTextSize(TEXT_SIZE);
        button.setTextColor(Color.YELLOW);
        button.setText(text);
        button.setBackground(buttonBg);
        return button;
    }

    // 按照顺序在PositionLayout中依次添加按钮的示例
    private void addComponents(PositionLayout linear, ShapeElement buttonBg) {
        // 构建显示注册流转任务管理服务的按钮
        Button btnRegister = createButton("register", buttonBg);
        btnRegister.setClickedListener(mRegisterListener);
        linear.addComponent(btnRegister);

        // 构建显示设备列表的按钮
        btnShowDeviceList = createButton("ShowDeviceList", buttonBg);
        btnShowDeviceList.setClickedListener(mShowDeviceListListener);
        linear.addComponent(btnShowDeviceList);

        // 构建远程启动FA/PA的按钮
        btnStartRemote = createButton("StartRemote", buttonBg);
        btnStartRemote.setClickedListener(mStartRemoteListener);
        linear.addComponent(btnStartRemote);

        // 构建远程关闭PA的按钮
        btnStopRemote = createButton("StopRemote", buttonBg);
        btnStopRemote.setClickedListener(mStopRemoteListener);
        linear.addComponent(btnStopRemote);

        // 构建连接远程PA的按钮
        btnConnectRemotePA = createButton("ConnectRemotePA", buttonBg);
        btnConnectRemotePA.setClickedListener(mConnectRemotePAListener);
        linear.addComponent(btnConnectRemotePA);

        // 构建控制连接PA的按钮
        btnControlRemotePA = createButton("ControlRemotePA", buttonBg);
        btnControlRemotePA.setClickedListener(mControlPAListener);
        linear.addComponent(btnControlRemotePA);

        // 构建与远程PA断开连接的按钮
        btnDisconnectRemotePA = createButton("DisconnectRemotePA", buttonBg);
        btnDisconnectRemotePA.setClickedListener(mDisconnectRemotePAListener);
        linear.addComponent(btnDisconnectRemotePA);

        // 打开MainAbility
        Button btnOpenLight = createButton("开灯", buttonBg);
        btnOpenLight.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (selectDeviceId != null) {
                    // 通过showDeviceList获取指定目标设备deviceId
                    // 指定待启动FA/PA的bundleName和abilityName
                    // 设置分布式标记，表明当前涉及分布式能力
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId(selectDeviceId)
                            .withBundleName(REMOTE_BUNDLE_NAME)
                            .withAbilityName(REMOTE_FA_NAME)
                            .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                            .build();
                    Intent startIntent = new Intent();
                    startIntent.setParam("light",1);
                    startIntent.setOperation(operation);
                    // 通过AbilitySlice包含的startAbility接口实现跨设备启动FA/PA
                    startAbility(startIntent);
                    LogUtil.info(TAG,"open light");
                } else {
                    btnStartRemote.setText("StartRemote selectDeviceId is null");
                }
            }
        });
        linear.addComponent(btnOpenLight);

        // 打开MainAbility
        Button btnCloseLight = createButton("关灯", buttonBg);
        btnCloseLight.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (selectDeviceId != null) {
                    // 通过showDeviceList获取指定目标设备deviceId
                    // 指定待启动FA/PA的bundleName和abilityName
                    // 设置分布式标记，表明当前涉及分布式能力
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId(selectDeviceId)
                            .withBundleName(REMOTE_BUNDLE_NAME)
                            .withAbilityName(REMOTE_FA_NAME)
                            .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                            .build();
                    Intent startIntent = new Intent();
                    startIntent.setParam("light",0);
                    startIntent.setOperation(operation);
                    // 通过AbilitySlice包含的startAbility接口实现跨设备启动FA/PA
                    startAbility(startIntent);
                    LogUtil.info(TAG,"close light");
                } else {
                    btnStartRemote.setText("StartRemote selectDeviceId is null");
                }
            }
        });
        linear.addComponent(btnCloseLight);


        // 打开MainAbility
        int powerNumber = new Random().nextInt(10);
        Button btnControlLightPower = createButton("灯亮度("+powerNumber+")", buttonBg);
        btnControlLightPower.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (selectDeviceId != null) {
                    // 通过showDeviceList获取指定目标设备deviceId
                    // 指定待启动FA/PA的bundleName和abilityName
                    // 设置分布式标记，表明当前涉及分布式能力
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId(selectDeviceId)
                            .withBundleName(REMOTE_BUNDLE_NAME)
                            .withAbilityName(REMOTE_FA_NAME)
                            .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                            .build();
                    Intent startIntent = new Intent();
                    startIntent.setParam("lightSize",powerNumber);
                    startIntent.setOperation(operation);
                    // 通过AbilitySlice包含的startAbility接口实现跨设备启动FA/PA
                    startAbility(startIntent);
                    LogUtil.info(TAG,"control light: "+powerNumber);
                } else {
                    btnStartRemote.setText("StartRemote selectDeviceId is null");
                }
            }
        });
        linear.addComponent(btnControlLightPower);


    }


    // 注册流转任务管理服务
    private Component.ClickedListener mRegisterListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            LogUtil.info(TAG, "register call.");
            //增加过滤条件
            ExtraParams params = new ExtraParams();
            String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
            params.setDevType(devTypes);
            String jsonParams = "{'filter':{'commonFilter':{'system':{'harmonyVersion':'2.0.0'},'groupType':'1|256','curComType': 0x00030004,'faFilter':'{\"localVersionCode\":1,\"localMinCompatibleVersionCode\":2,\"targetBundleName\": \"com.xxx.yyy\"}'}},'transferScene':0,'remoteAuthenticationDescription': '拉起HiVision扫描弹框描述','remoteAuthenticationPicture':''}";
            params.setJsonParams(jsonParams);
            continuationRegisterManager.register(BUNDLE_NAME, params, callback, requestCallback);
        }
    };
    // 显示设备列表，获取设备信息
    private Component.ClickedListener mShowDeviceListListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            // 设置过滤设备类型
            ExtraParams params = new ExtraParams();
            String[] devTypes = new String[]{ExtraParams.DEVICETYPE_SMART_PAD, ExtraParams.DEVICETYPE_SMART_PHONE};
            params.setDevType(devTypes);
            String jsonParams = "{'filter':{'commonFilter':{'system':{'harmonyVersion':'2.0.0'},'groupType':'1|256','curComType': 0x00030004,'faFilter':'{\"localVersionCode\":1,\"localMinCompatibleVersionCode\":2,\"targetBundleName\": \"com.xxx.yyy\"}'}},'transferScene':0,'remoteAuthenticationDescription': '拉起HiVision扫描弹框描述','remoteAuthenticationPicture':''}";
            params.setJsonParams(jsonParams);
            // 显示选择设备列表
            continuationRegisterManager.showDeviceList(abilityToken, params, null);
        }
    };

    // 启动远程FA/PA
    private Component.ClickedListener mStartRemoteListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            if (selectDeviceId != null) {
                // 通过showDeviceList获取指定目标设备deviceId
                // 指定待启动FA/PA的bundleName和abilityName
                // 设置分布式标记，表明当前涉及分布式能力
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId(selectDeviceId)
                        .withBundleName(REMOTE_BUNDLE_NAME)
                        .withAbilityName(REMOTE_FA_NAME)
                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                        .build();
                Intent startIntent = new Intent();
                startIntent.setOperation(operation);
                // 通过AbilitySlice包含的startAbility接口实现跨设备启动FA/PA
                startAbility(startIntent);
            } else {
                btnStartRemote.setText("StartRemote selectDeviceId is null");
            }
        }
    };

    // 关闭远程PA
    private Component.ClickedListener mStopRemoteListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            if (selectDeviceId != null) {
                // 通过showDeviceList获取指定目标设备deviceId
                // 指定待关闭PA的bundleName和abilityName
                // 设置分布式标记，表明当前涉及分布式能力
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId(selectDeviceId)
                        .withBundleName(REMOTE_BUNDLE_NAME)
                        .withAbilityName(REMOTE_PA_NAME)
                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                        .build();
                Intent stopIntent = new Intent();
                stopIntent.setOperation(operation);
                // 通过AbilitySlice包含的stopAbility接口实现跨设备关闭PA
                stopAbility(stopIntent);
            } else {
                btnStopRemote.setText("StopRemote selectDeviceId is null");
            }
        }
    };


    // 连接远程PA
    private Component.ClickedListener mConnectRemotePAListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            if (selectDeviceId != null) {
                // 指定待连接PA的bundleName和abilityName
                // 设置分布式标记，表明当前涉及分布式能力
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId(selectDeviceId)
                        .withBundleName(REMOTE_BUNDLE_NAME)
                        .withAbilityName(REMOTE_PA_NAME)
                        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                        .build();
                Intent connectPAIntent = new Intent();
                connectPAIntent.setOperation(operation);
                // 通过AbilitySlice包含的connectAbility接口实现跨设备连接PA
                connectAbility(connectPAIntent, mConn);
            }
        }
    };

    // 控制已连接PA执行加法
    private Component.ClickedListener mControlPAListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            if (mProxy != null) {
                int ret = -1;
                try {
                    ret = mProxy.plus(10, 20);
                } catch (RemoteException e) {
                    LogUtil.error(TAG, "ControlRemotePA error");
                }
                btnControlRemotePA.setText("ControlRemotePA result = " + ret);
            }
        }
    };

    // 与远程PA断开连接
    private Component.ClickedListener mDisconnectRemotePAListener = new Component.ClickedListener() {
        @Override
        public void onClick(Component arg0) {
            // 按钮复位
            btnConnectRemotePA.setText("ConnectRemotePA");
            btnControlRemotePA.setText("ControlRemotePA");
            disconnectAbility(mConn);
        }
    };
    // 当连接完成时，用来提供管理已连接PA的能力
    private MyRemoteProxy mProxy = null;
    // 用于管理连接关系
    private IAbilityConnection mConn = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName element, IRemoteObject remote, int resultCode) {
            // 跨设备PA连接完成后，会返回一个序列化的IRemoteObject对象
            // 通过该对象得到控制远端服务的代理
            mProxy = new MyRemoteProxy(remote);
            btnConnectRemotePA.setText("connectRemoteAbility done");
        }

        @Override
        public void onAbilityDisconnectDone(ElementName element, int resultCode) {
            // 当已连接的远端PA异常关闭时，会触发该回调
            // 支持开发者按照返回的错误信息进行PA生命周期管理
            disconnectAbility(mConn);
        }
    };

}
